<?php
/**
 * Gestione delle sessioni utenti
 *
 */
class session
{
	
	private $login;
	public $login_error;
	private $db;
	private $userid;
	
	private $auth;
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $dbhost
	 * @param unknown_type $dbname
	 * @param unknown_type $dbuser
	 * @param unknown_type $dbpass
	 * @param unknown_type $dbtable
	 * @param unknown_type $fielduser
	 * @param unknown_type $fieldpassword
	 * @param unknown_type $fielduserid
	 */
	public function __construct()
	{
		session_start();
		include 'auth/'.config::getconfig("_auth_type").'.class.php';
		$this->auth = new auth();
		$this->sesssionExists();
	}
	
	/**
	 * Enter description here...
	 *
	 * @return unknown
	 */
	public function sesssionExists()
	{
		if($this->sessionVerify())
		{
			return TRUE;	
		}
		else
		{
			if($this->userLoginVerify())
			{
				return TRUE;
			}
			else
			{
				return FALSE;
			}
		}			
	}
	

	/**
	 * Enter description here...
	 *
	 * @return unknown
	 */
	private function sessionVerify()
	{	
		if (is_null($_SESSION['userid']) or is_null($_SESSION['hash']))
		{		
			return FALSE;
		}
		else
		{
			if($this->auth->isOnline())
			{				
				return TRUE;
			}
			else
			{
				return FALSE;
			}

		}
	}
	
	/**
	 * Enter description here...
	 *
	 * @return unknown
	 */
	private function userLoginVerify()
	{

		if (is_null($_POST['user']) or is_null($_POST['password']))
		{
			return FALSE;
		}
		else
		{
			$session_array = $this->auth->isAuthenticate();
			if(is_array($session_array))
			{
				$db = db::getDbIstance();
				$db->query("SELECT userid FROM user WHERE username = '{$session_array['username']}'");
				if($db->num_rows())
				{
					list($userid) = $db->fetch_row();
					$_SESSION['userid'] = $userid;
				}
				$_SESSION['hash'] = $session_array['hash'];
				$_SESSION['username'] = $session_array['username'];
				return TRUE;
			}
			else
			{
				return FALSE;	
			}	
		}
	}

	/**
	 * Enter description here...
	 *
	 */
	public function logout()
	{
		session_unset();
		session_destroy();
	}

	private function set_cookie()
	{
		$string = session_encode();
		setcookie("rdagp",$string,time() + $this->config['cookie_lifetime'],"/".$this->config['main_dir']."/",$this->config['cookie_domain']);		
	}
	
	private function unset_cookie()
	{
		setcookie("rdagp","",time -3600);	
		
	}
	private function get_cookie(){
			session_decode($_COOKIE['rdagp']);
	}
}
?>